<template>
	<view class="animated fadeIn faster page-bg">
		<NoticeBar :notices="notices" />

		<view class="mx-2 my-2">
			<swiper indicator-dots autoplay :interval="5000" :duration="1000" indicator-active-color="#ffffff"
				indicator-color="#c6c8c5" class="position-relative"
				style="width:100%;height: 300rpx;border-radius:30rpx;overflow: hidden;">
				<block v-for="(item,idx) in banner" :key="idx+'a'">
					<swiper-item>
						<view class="swiper-item">
							<image :src="item.image" mode="aspectFill" lazy-load
								style="width:100%;height: 300rpx;border-radius: 30rpx;" @click="goUrl(item.url)">
							</image>
						</view>
					</swiper-item>
				</block>
			</swiper>
		</view>

		<view class="mx-2 py-1 bg-fff category d-flex  d-flex-middle d-flex-wrap rounded20">
			<view v-for="(item,inde) in categoryList.slice(0,4)" :key="inde+'c'" style="width: 140rpx"
				@click="clickCategory(item,inde)" class="d-flex-column d-flex-middle my-1">
				<view class="cate rounded20" :class="{'cateActive':categoryIndex == inde}">
					<image :src="item.icon" class="rounded20 cateImg"></image>
				</view>
				<text class="font24 mt-1">{{ item.name }}</text>
			</view>
			<view v-if="categoryList.length>3" style="width: 20%" class="d-flex-column d-flex-middle my-1"
				@click="openCate">
				<view class="iconfont icon-a-fenleipinlei font80 color598dfc"></view>
				<text class="font24 mt-1 ">更多品类</text>
			</view>
		</view>

		<view class="mx-2 my-2  bg-fff grabClass rounded10">
			<scroll-view class="tab-scroll" scroll-x="true" scroll-with-animation :scroll-left="scrollLeft">
				<view class="tab-scroll_box">
					<view v-for="(item,index) in listType" :key="index+'1'" class="tab-scroll_item px-4 py-1"
						@click="getType(item.id,index)" :class="{'grabClassActive':tabsIndex == item.id}">
						{{ item.name }}
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="mx-2 my-2" v-if="list.length>0">
			<!-- <view class="font-bold font36 text-center my-2">护航单</view> -->
			<view class="d-flex  d-flex-middle d-flex-wrap d-flex-between">
				<view v-for="(item,inde) in list" :key="inde+'c'" style="width: 46%" class="p-1 bg-fff rounded20 mb-2"
					@click="goUrl('/subPages/placeAnOrder/placeAnOrder',item)">
					<image :src="item.icon" class="img"></image>
					<view class="d-flex d-flex-item d-flex-column d-flex-between pb-1">
						<view class="font-bold font30 mt-1 text-clamp">{{ item.name }}</view>
						<view class="text-clamp-two font26 my-1 color999 ch_h">{{ item.introduce }}</view>
						<view class="d-flex d-flex-middle d-flex-between">
							<view class="d-flex d-flex-column font26 " style="width: 200rpx;">
								<view>

									<text class="font36 colorf00">
										<text class="font22">￥</text>
										{{ formatPrice(item.price).integer }}
									</text>
									<text class="colorf00 font22" v-if="formatPrice(item.price).decimal">
										.{{ formatPrice(item.price).decimal }}
									</text>
									<text class="color999 font22 ml-1-5" v-if="item.price.length<4"
										style="text-decoration: line-through">{{ Number(item.price) + 50 }}
									</text>
								</view>
								<!-- <text class="colorprice color999 font24">销量4.6k浏览4.7k</text> -->
							</view>
							<view class="bgcolor598dfc px-1 py-1 rounded40 colorfff font22">我要下单
							</view>
						</view>

					</view>
				</view>
			</view>
		</view>

		<view class="load-more d-flex d-flex-center d-flex-column d-flex-middle">
			<image class="mb-2" v-if="loadingType == 2 && list.length == 0"
				src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png"
				style="width: 198rpx;height: 128rpx;margin-top: 260rpx;"></image>
			<text>{{ loadingType === 0 ? '上拉显示更多' : (loadingType === 1 ? '正在加载...' : '~ 没有更多数据了 ~') }}</text>
		</view>

		<uni-popup :safe-area="false" ref="catePopup" @touchmove.stop.prevent="moveHandle" type="bottom"
			style="position: relative;z-index: 999991;">
			<view class="wrap">
				<view class="py-3 d-flex d-flex-between d-flex-middle mb-3">
					<view style="width: 150rpx;"></view>
					<text class="font30 color000">游戏分类</text>
					<view class="d-flex d-flex-middle d-flex-end pr-3" style="width: 120rpx;"><text
							class="iconfont icon-cuo font30 color999" @click="closeCate"></text></view>
				</view>
				<view class="pb-2 px-1">
					<scroll-view style="height: 500rpx;" scroll-y="true" enableBackToTop="true" :scroll-top="0"
						scroll-with-animation>
						<view class="row">
							<view class="span-4 d-flex d-flex-column d-flex-middle d-flex-center mb-3"
								v-for="(cate,index) in allCategory" :key="cate.id" :class="{'cate-on':cateIndex==index}"
								@click="setCate(index,cate.id)">
								<image :src="cate.icon" class="mb-1 cate-img"></image>
								<text class="font24">{{cate.name}}</text>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>

		<view class="fab  d-flex" @click="goUrl('/subPages/rankingList/rankingList')">
			<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/changelog-task.png"
				class="fab-img mr-1"></image>
			<text>富豪榜</text>
		</view>
	</view>
</template>

<script>
	import NoticeBar from '@/components/notice-bar/index.vue'
	import {
		homeApi
	} from '@/http/homeApi.js';
	import {
		mapState
	} from "vuex"
	import store from "@/store";

	export default {
		components: {
			NoticeBar
		},
		computed: {
			...mapState({
				loginState: state => state.loginState,
				user_id: state => state.id,
				homeSettingFlag: state => state.homeSettingFlag
			})
		},
		data() {
			return {
				notices: [],
				banner: [],
				categoryList: [],
				allCategory: [],
				cateIndex: -1,
				list: [],
				listType: [],
				tabsIndex: '',
				loadingType: 1,
				page: 1,
				categoryIndex: -1,
				scrollLeft: 0,
				sWidth: 0
			}
		},
		async onLoad(e) {
			if (e && e.invite) {
				store.commit('setInviteCode', e.invite)
			}
			await this.SwiperBanner();
			await this.categories();
			await this.carryType()
			await this.carry(this.tabsIndex);
		},
		async onShow() {
			if (this.homeSettingFlag) {
				store.commit('setHomeSettingFlag', false)
				this.page = 1;
				this.notices = []
				this.banner = []
				this.categoryList = []
				this.list = []
				this.listType = []
				await this.SwiperBanner();
				await this.categories();
				await this.carryType()
				await this.carry(this.tabsIndex);
			}
		},
		onReachBottom() {
			if (this.loadingType == 2 || this.loadingType == 1) {
				return;
			}
			this.page++
			this.carry(this.tabsIndex);
		},
		methods: {
			async SwiperBanner() {
				let res = await homeApi.getBanner('1')
				let res1 = await homeApi.getBanner('2')
				this.notices = res1
				if (res.length > 0) {
					this.banner = res
				} else {
					this.banner = [{
						id: 1,
						image: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/banner.png'
					}]
				}
			},
			async categories() {
				let res = await homeApi.getMyGame(this.user_id)
				this.categoryList = res
			},
			async carryType() {
				let res = await homeApi.getCarryType()
				this.listType = res;
				this.tabsIndex = res[0].id
				setTimeout(() => {
					this.getScrollW()
				}, 500)
			},
			getScrollW() {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.tab-scroll_item').boundingClientRect(data => {
					this.sWidth = data[0].width
				}).exec()
			},
			async carry(type, id) {
				if (!id) id = ''
				let that = this
				that.loadingType = 1
				try {
					let params = {
						game_type: '',
						game_login_type: '',
						type: type,
						page: that.page,
						game_id: id
					}
					let result = await homeApi.getCarry(params)
					if (result.data) {
						that.list = that.list.concat(result.data)
					}
					if (result.data && result.data.length > 9) {
						that.loadingType = 0
					} else {
						that.loadingType = 2
					}
				} catch (error) {
					that.loadingType = 2
				}
			},
			goUrl(urlPages, data) {
				if (!this.loginState) {
					uni.showToast({
						title: '未登录，请先登录！',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1500)
				} else {
					if (data) {
						uni.navigateTo({
							url: `${urlPages}?data=${encodeURIComponent(JSON.stringify(data))}`
						})
					} else {
						uni.navigateTo({
							url: urlPages
						})
					}

				}
			},
		   getType(e, index) {
		      this.tabsIndex = e;
		      this.scrollLeft = 0;
		
		      // 计算需要滚动的距离，使选中的标签居中
		      const itemWidth = 120; // 假设每个标签平均宽度
		      const containerWidth = uni.getSystemInfoSync().windowWidth; // 减去左右margin
		      const targetPosition = index * itemWidth;
		      const centerPosition = targetPosition - (containerWidth / 2) + (itemWidth / 2);
		
		      this.scrollLeft = Math.max(0, centerPosition);
		
		      this.list = [];
		      this.page = 1;
		      if (e === 'recommend') {
		        this.carry('recommend');
		      } else {
		        this.carry(e);
		      }
		    },
			clickCategory(e, index) {
				this.categoryIndex = index
				this.cateIndex = -1
				this.list = [];
				this.page = 1;
				this.carry(this.tabsIndex, e.id)
			},
			getAllCate() {
				let that = this
				uni.showLoading({
					title: '加载中...'
				})
				homeApi.getAllCategory().then((res) => {
					uni.hideLoading()
					that.allCategory = res
				}).catch((err) => {
					uni.hideLoading()
					console.log('err', err)
				})
			},
			setCate(index, id) {
				let that = this
				that.categoryIndex = -1
				that.cateIndex = index
				that.list = [];
				that.page = 1;
				that.$refs.catePopup.close()
				that.carry(that.tabsIndex, id)
			},
			moveHandle() {
				return false
			},
			openCate() {
				if (this.allCategory.length == 0) {
					this.getAllCate()
				}
				this.$refs.catePopup.open()
			},
			closeCate() {
				this.$refs.catePopup.close()
			},
			formatPrice(price) {
				if (!price) return {
					integer: '0',
					decimal: ''
				};

				// 转换为浮点数并保留两位小数
				const priceNum = parseFloat(price);
				if (isNaN(priceNum)) return {
					integer: '0',
					decimal: ''
				};

				const formattedPrice = priceNum.toFixed(2);
				const parts = formattedPrice.split('.');

				// 整数部分
				const integer = parts[0];

				// 小数部分（如果有且不为00）
				const decimal = parts[1] && parts[1] !== '00' ? `.${parts[1]}` : '00';

				return {
					integer,
					decimal
				};
			}
		}
	}
</script>

<style scoped>
	.font80 {
		font-size: 80rpx;
	}

	.color598dfc {
		color: #598dfc;
	}

	.bgcolor598dfc {
		background-color: #598dfc;
	}

	.img {
		width: 328rpx;
		height: 308rpx;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
	}

	.ch_h {
		height: 68rpx;
	}

	.grabClass {
		overflow: hidden;
	}

	.grabClass view {
		border-right: 2rpx solid #f4f6fa;
	}

	.grabClass view:last-child {
		border-right: 0 solid #f4f6fa;
	}

	.grabClassActive {
		background-color: #598dfc;
		color: #fff;
	}

	.cateActive {
		background: #aec8ff;
	}

	.cate {
		width: 84rpx;
		height: 84rpx;
		overflow: hidden;
		border: 8rpx solid transparent;
	}

	.cateImg {
		width: 84rpx;
		height: 84rpx;
	}

	.tab-scroll {
		flex: 1;
		overflow: hidden;
		box-sizing: border-box;
	}

	.tab-scroll_box {
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
		box-sizing: border-box;

	}

	.tab-scroll_item {
		flex-shrink: 0;
		display: flex;
		justify-content: center;
	}

	.cate-on {
		color: #598dfc;
	}

	.cate-img {
		width: 80rpx;
		height: 80rpx;
		border-radius: 20rpx;
		border: solid 2px #ffffff;
	}

	.cate-on .cate-img {
		border: solid 2px #598dfc;
	}

	.fab {
		position: fixed;
		right: 15px;
		top: 170px;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 80px;
		height: 35px;
		background: rgb(239, 206, 121);
		background-size: 400% 400%;
		animation: float 4s ease-in-out infinite;
		border-radius: 30px;
		z-index: 11;
		font-size: 14px;
		color: #000000;
		box-shadow: 0 3px 0 rgb(170, 157, 66)
	}

	.fab-img {
		width: 30rpx;
		height: 30rpx;
	}

	@keyframes goldShine {
		0% {
			background-position: 0% 50%;
		}

		50% {
			background-position: 100% 50%;
		}

		100% {
			background-position: 0% 50%;
		}
	}


	@keyframes float {
		0% {
			transform: translateY(0px);
		}

		50% {
			transform: translateY(-6px);
		}

		100% {
			transform: translateY(0px);
		}
	}
</style>